#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 基础URL
BASE_URL="http://localhost:8000/api/v1"
TOKEN=""
SUMMARY_ID=""

# 测试结果统计
TOTAL_TESTS=0
PASSED_TESTS=0

# 辅助函数
print_test_result() {
    local test_name=$1
    local result=$2
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    if [ $result -eq 0 ]; then
        echo -e "${GREEN}✓ $test_name passed${NC}"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "${RED}✗ $test_name failed${NC}"
    fi
}

# 获取用户token
get_user_token() {
    response=$(curl -s -X POST "${BASE_URL}/user/login/" \
        -H "Content-Type: application/json" \
        -d '{
            "username": "analyst1",
            "password": "analyst123"
        }')
    
    if [[ $response == *'"code":200'* ]]; then
        TOKEN=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin)['data']['token'])")
    else
        echo "Failed to get token: $response"
        exit 1
    fi
}

# 1. 测试创建总结
test_create_summary() {
    echo -e "\n${YELLOW}Testing Create Summary...${NC}"
    
    response=$(curl -s -X POST "${BASE_URL}/phase-summary/" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d '{
            "title": "2024年Q1总结",
            "phase": {
                "start": "2024-01-01",
                "end": "2024-03-31"
            },
            "content": {
                "overview": "第一季度工作总结",
                "achievements": [
                    {
                        "title": "主要成果1",
                        "description": "详细描述",
                        "metrics": [
                            {
                                "name": "完成率",
                                "value": 95.5,
                                "unit": "%"
                            }
                        ]
                    }
                ],
                "problems": [
                    {
                        "title": "问题1",
                        "description": "问题描述",
                        "solution": "解决方案"
                    }
                ],
                "next_plan": "下季度计划"
            },
            "tags": ["2024", "Q1"],
            "status": "draft"
        }')
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        SUMMARY_ID=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin)['data']['summary_id'])")
        print_test_result "Create Summary" 0
    else
        print_test_result "Create Summary" 1
    fi
}

# 2. 测试获取总结列表
test_get_summary_list() {
    echo -e "\n${YELLOW}Testing Get Summary List...${NC}"
    
    response=$(curl -s -X GET "${BASE_URL}/phase-summary/" \
        -H "Authorization: Bearer ${TOKEN}")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "Get Summary List" 0
    else
        print_test_result "Get Summary List" 1
    fi
}

# 3. 测试获取总结详情
test_get_summary_detail() {
    echo -e "\n${YELLOW}Testing Get Summary Detail...${NC}"
    
    if [ -z "$SUMMARY_ID" ]; then
        echo "No summary ID available"
        print_test_result "Get Summary Detail" 1
        return
    fi
    
    response=$(curl -s -X GET "${BASE_URL}/phase-summary/${SUMMARY_ID}/" \
        -H "Authorization: Bearer ${TOKEN}")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "Get Summary Detail" 0
    else
        print_test_result "Get Summary Detail" 1
    fi
}

# 4. 测试更新总结
test_update_summary() {
    echo -e "\n${YELLOW}Testing Update Summary...${NC}"
    
    if [ -z "$SUMMARY_ID" ]; then
        echo "No summary ID available"
        print_test_result "Update Summary" 1
        return
    fi
    
    response=$(curl -s -X PUT "${BASE_URL}/phase-summary/${SUMMARY_ID}/" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d '{
            "title": "更新后的总结标题",
            "phase": {
                "start": "2024-02-01",
                "end": "2024-03-31"
            },
            "content": {
                "overview": "更新后的总结概述",
                "achievements": [
                    {
                        "title": "更新的成果1",
                        "description": "更新的描述",
                        "metrics": [
                            {
                                "name": "完成率",
                                "value": 98.5,
                                "unit": "%"
                            }
                        ]
                    }
                ],
                "problems": [
                    {
                        "title": "更新的问题1",
                        "description": "更新的问题描述",
                        "solution": "更新的解决方案"
                    }
                ],
                "next_plan": "更新的下季度计划"
            },
            "tags": ["2024", "Q1", "updated"],
            "status": "published"
        }')
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "Update Summary" 0
    else
        print_test_result "Update Summary" 1
    fi
}

# 5. 测试删除总结
test_delete_summary() {
    echo -e "\n${YELLOW}Testing Delete Summary...${NC}"
    
    if [ -z "$SUMMARY_ID" ]; then
        echo "No summary ID available"
        print_test_result "Delete Summary" 1
        return
    fi
    
    response=$(curl -s -X DELETE "${BASE_URL}/phase-summary/${SUMMARY_ID}/" \
        -H "Authorization: Bearer ${TOKEN}")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "Delete Summary" 0
    else
        print_test_result "Delete Summary" 1
    fi
}

# 6. 测试未授权访问
test_unauthorized_access() {
    echo -e "\n${YELLOW}Testing Unauthorized Access...${NC}"
    
    response=$(curl -s -X GET "${BASE_URL}/phase-summary/")
    
    echo "Response: $response"
    if [[ $response == *'"detail":"身份认证信息未提供。"'* ]]; then
        print_test_result "Unauthorized Access" 0
    else
        print_test_result "Unauthorized Access" 1
    fi
}

# 运行所有测试
run_all_tests() {
    echo -e "${YELLOW}Starting Phase Summary API Tests...${NC}"
    
    # 获取token
    get_user_token
    
    # 运行测试
    test_create_summary
    test_get_summary_list
    test_get_summary_detail
    test_update_summary
    test_delete_summary
    test_unauthorized_access
    
    echo -e "\n${YELLOW}Test Results:${NC}"
    echo -e "Total Tests: $TOTAL_TESTS"
    echo -e "Passed: ${GREEN}$PASSED_TESTS${NC}"
    echo -e "Failed: ${RED}$((TOTAL_TESTS - PASSED_TESTS))${NC}"
}

# 执行测试
run_all_tests